import React, { useState, useEffect } from 'react';
import { Button, Space, Tag, message, Modal, Form, Input, Select, InputNumber, Descriptions, List, Tooltip, Drawer, Card, Row, Col, DatePicker } from 'antd';
import { ShoppingOutlined, EyeOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, UserOutlined, PlusOutlined, MoreOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import SearchForm, { SearchFieldConfig } from '@/components/SearchForm';
import DataTable, { PaginationConfig, ToolbarAction, BatchAction } from '@/components/DataTable';
import type { ColumnsType } from 'antd/es/table';
import {
  getOrderList,
  getOrderDetail,
  updateOrderStatus,
  batchUpdateOrderStatus,
  deleteOrder,
  type Order,
  type OrderQueryParams,
  type UpdateOrderStatusRequest,
  type OrderItem
} from '@/services/orders';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

// 安全的金额格式化函数
const formatAmount = (amount: any): string => {
  const numAmount = typeof amount === 'number' ? amount : parseFloat(amount) || 0;
  return numAmount.toFixed(2);
};

const OrderList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState<Order[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // 状态更新相关
  const [statusModalVisible, setStatusModalVisible] = useState(false);
  const [batchStatusModalVisible, setBatchStatusModalVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState<Order | null>(null);
  
  // 订单详情
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [orderDetail, setOrderDetail] = useState<Order | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  const [searchForm] = Form.useForm();
  const [statusForm] = Form.useForm();
  const [batchStatusForm] = Form.useForm();

  // 订单状态映射
  const orderStatusOptions = [
    { value: 'pending', label: '待处理', color: 'orange' },
    { value: 'confirmed', label: '已确认', color: 'blue' },
    { value: 'processing', label: '处理中', color: 'purple' },
    { value: 'shipped', label: '已发货', color: 'cyan' },
    { value: 'delivered', label: '已送达', color: 'green' },
    { value: 'completed', label: '已完成', color: 'success' },
    { value: 'cancelled', label: '已取消', color: 'red' }
  ];

  // 支付状态映射
  const paymentStatusOptions = [
    { value: 'pending', label: '待支付', color: 'orange' },
    { value: 'paid', label: '已支付', color: 'green' },
    { value: 'failed', label: '支付失败', color: 'red' },
    { value: 'refunded', label: '已退款', color: 'purple' },
    { value: 'partial_refund', label: '部分退款', color: 'blue' }
  ];

  const getStatusConfig = (status: string, type: 'order' | 'payment') => {
    const options = type === 'order' ? orderStatusOptions : paymentStatusOptions;
    return options.find(opt => opt.value === status) || { value: status, label: status, color: 'default' };
  };

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      name: 'keyword',
      type: 'input',
      placeholder: '订单号/客户名/邮箱',
      width: 200,
      prefix: <SearchOutlined />
    },
    {
      name: 'status',
      type: 'select',
      placeholder: '选择订单状态',
      width: 120,
      options: orderStatusOptions
    },
    {
      name: 'paymentStatus',
      type: 'select',
      placeholder: '选择支付状态',
      width: 120,
      options: paymentStatusOptions
    },
    {
      name: 'dateRange',
      type: 'dateRange',
      placeholder: '创建时间'
    },
    {
      name: 'minAmount',
      type: 'input',
      placeholder: '最低金额',
      width: 100
    },
    {
      name: 'maxAmount',
      type: 'input',
      placeholder: '最高金额',
      width: 100
    }
  ];

  // 表格列配置
  const columns: ColumnsType<Order> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '订单号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 180,
      render: (orderNumber: string) => (
        <span className="font-mono text-sm">{orderNumber}</span>
      ),
    },
    {
      title: '客户信息',
      key: 'customer',
      width: 200,
      render: (record: Order) => (
        <div>
          <div className="font-medium">{record.customerInfo?.nickname || record.customerInfo?.username}</div>
          <div className="text-sm text-gray-500">{record.customerInfo?.email}</div>
        </div>
      ),
    },
    {
      title: '订单金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      render: (amount: any) => (
        <span className="font-medium text-lg">¥{formatAmount(amount)}</span>
      ),
    },
    {
      title: '商品数量',
      key: 'items',
      width: 120,
      render: (record: Order) => (
        <div className="text-center">
          <div className="font-medium">{record.itemStats?.itemCount || 0}</div>
          <div className="text-sm text-gray-500">共{record.itemStats?.totalQuantity || 0}件</div>
        </div>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = getStatusConfig(status, 'order');
        return <Tag color={config.color}>{config.label}</Tag>;
      },
    },
    {
      title: '支付状态',
      dataIndex: 'payment_status',
      key: 'payment_status',
      width: 100,
      render: (status: string) => {
        const config = getStatusConfig(status, 'payment');
        return <Tag color={config.color}>{config.label}</Tag>;
      },
    },
    {
      title: '支付方式',
      dataIndex: 'payment_method',
      key: 'payment_method',
      width: 100,
      render: (method: string) => method || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 200,
      render: (record: Order) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="更新状态">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleUpdateStatus(record)}
            />
          </Tooltip>
          <Tooltip title="删除订单">
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record)}
              disabled={!['cancelled', 'completed'].includes(record.status)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];



  // 获取订单列表
  const fetchData = async (page: number = currentPage, size: number = pageSize) => {
    try {
      setLoading(true);
      const searchValues = searchForm.getFieldsValue();
      const { dateRange, ...otherValues } = searchValues;

      const params: OrderQueryParams = {
        page,
        limit: size,
        ...otherValues,
      };

      // 处理日期范围
      if (dateRange && dateRange.length === 2) {
        params.startDate = dateRange[0].format('YYYY-MM-DD');
        params.endDate = dateRange[1].format('YYYY-MM-DD');
      }

      const response = await getOrderList(params);

      if (response.success) {
        setOrders(response.data.items || []);
        setTotal(response.data.pagination.total);
        setCurrentPage(page);
        setPageSize(size);
      } else {
        message.error(response.message || '获取订单列表失败');
      }
    } catch (error) {
      console.error('获取订单列表失败:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 查看订单详情
  const handleViewDetail = async (record: Order) => {
    try {
      setDetailLoading(true);
      setDetailDrawerVisible(true);
      
      const response = await getOrderDetail(record.id);
      if (response.success) {
        setOrderDetail(response.data);
      } else {
        message.error(response.message || '获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情失败:', error);
      message.error('获取订单详情失败');
    } finally {
      setDetailLoading(false);
    }
  };

  // 更新单个订单状态
  const handleUpdateStatus = (record: Order) => {
    setCurrentOrder(record);
    statusForm.setFieldsValue({
      status: record.status,
      payment_status: record.payment_status,
      notes: record.notes || '',
    });
    setStatusModalVisible(true);
  };

  // 批量更新状态
  const handleBatchUpdateStatus = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要更新的订单');
      return;
    }
    setBatchStatusModalVisible(true);
  };

  // 删除订单
  const handleDelete = (record: Order) => {
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除订单 "${record.order_number}" 吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await deleteOrder(record.id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 提交状态更新
  const handleStatusSubmit = async () => {
    try {
      const values = await statusForm.validateFields();
      if (!currentOrder) return;

      const updateData: UpdateOrderStatusRequest = {};
      if (values.status !== currentOrder.status) {
        updateData.status = values.status;
      }
      if (values.payment_status !== currentOrder.payment_status) {
        updateData.payment_status = values.payment_status;
      }
      if (values.notes !== currentOrder.notes) {
        updateData.notes = values.notes;
      }

      if (Object.keys(updateData).length === 0) {
        message.warning('没有需要更新的内容');
        return;
      }

      await updateOrderStatus(currentOrder.id, updateData);
      message.success('状态更新成功');
      setStatusModalVisible(false);
      fetchData();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 提交批量状态更新
  const handleBatchStatusSubmit = async () => {
    try {
      const values = await batchStatusForm.validateFields();
      
      if (!values.status && !values.payment_status) {
        message.warning('请至少选择一个要更新的状态');
        return;
      }

      await batchUpdateOrderStatus({
        ids: selectedRowKeys as number[],
        status: values.status,
        payment_status: values.payment_status,
      });

      message.success('批量更新成功');
      setBatchStatusModalVisible(false);
      setSelectedRowKeys([]);
      fetchData();
    } catch (error) {
      message.error('批量更新失败');
    }
  };

  // 事件处理
  const handleSearch = () => {
    fetchData(1, pageSize);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchData(1, pageSize);
  };

  const handleTableChange = (page: number, pageSize?: number) => {
    fetchData(page, pageSize || 20);
  };

  // 工具栏操作配置
  const toolbarActions: ToolbarAction[] = [];

  // 批量操作配置
  const batchActions: BatchAction[] = [
    {
      key: 'batchUpdate',
      label: '批量更新状态',
      icon: <EditOutlined />,
      onClick: handleBatchUpdateStatus,
    },
  ];

  // 分页配置
  const paginationConfig: PaginationConfig = {
    current: currentPage,
    pageSize: pageSize,
    total: total,
    showTotal: (total: number) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: handleTableChange,
  };

  // 行选择配置
  const rowSelectionConfig = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    getCheckboxProps: (record: Order) => ({
      disabled: ['cancelled', 'completed'].includes(record.status),
    }),
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="space-y-6">
      {/* 搜索区域 */}
      <SearchForm
        fields={searchFields}
        form={searchForm}
        onSearch={handleSearch}
        onReset={handleReset}
        loading={loading}
      />

      {/* 订单列表 */}
      <DataTable<Order>
        title="订单列表"
        columns={columns}
        dataSource={orders}
        rowKey="id"
        loading={loading}
        pagination={paginationConfig}
        rowSelection={rowSelectionConfig}
        toolbarActions={toolbarActions}
        batchActions={batchActions}
        scroll={{ x: 1400 }}
      />

      {/* 单个订单状态更新模态框 */}
      <Modal
        title="更新订单状态"
        open={statusModalVisible}
        onOk={handleStatusSubmit}
        onCancel={() => setStatusModalVisible(false)}
        width={500}
      >
        <Form form={statusForm} layout="vertical">
          <Form.Item name="status" label="订单状态">
            <Select>
              {orderStatusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  <Tag color={option.color}>{option.label}</Tag>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="payment_status" label="支付状态">
            <Select>
              {paymentStatusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  <Tag color={option.color}>{option.label}</Tag>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={3} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 批量状态更新模态框 */}
      <Modal
        title={`批量更新状态 (${selectedRowKeys.length}个订单)`}
        open={batchStatusModalVisible}
        onOk={handleBatchStatusSubmit}
        onCancel={() => setBatchStatusModalVisible(false)}
        width={500}
      >
        <Form form={batchStatusForm} layout="vertical">
          <Form.Item name="status" label="订单状态" extra="留空表示不更新此状态">
            <Select placeholder="请选择订单状态" allowClear>
              {orderStatusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  <Tag color={option.color}>{option.label}</Tag>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="payment_status" label="支付状态" extra="留空表示不更新此状态">
            <Select placeholder="请选择支付状态" allowClear>
              {paymentStatusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  <Tag color={option.color}>{option.label}</Tag>
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 订单详情抽屉 */}
      <Drawer
        title="订单详情"
        width={800}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
        loading={detailLoading}
      >
        {orderDetail && (
          <div className="space-y-6">
            {/* 基本信息 */}
            <Card title="订单信息" size="small">
              <Descriptions column={2} size="small">
                <Descriptions.Item label="订单号">{orderDetail.order_number}</Descriptions.Item>
                <Descriptions.Item label="订单ID">{orderDetail.id}</Descriptions.Item>
                <Descriptions.Item label="订单状态">
                  <Tag color={getStatusConfig(orderDetail.status, 'order').color}>
                    {getStatusConfig(orderDetail.status, 'order').label}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="支付状态">
                  <Tag color={getStatusConfig(orderDetail.payment_status, 'payment').color}>
                    {getStatusConfig(orderDetail.payment_status, 'payment').label}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="支付方式">{orderDetail.payment_method || '-'}</Descriptions.Item>
                <Descriptions.Item label="订单金额">
                  <span className="text-lg font-medium text-red-500">¥{formatAmount(orderDetail.total_amount)}</span>
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {dayjs(orderDetail.created_at).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {dayjs(orderDetail.updated_at).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
              </Descriptions>
              
              {orderDetail.notes && (
                <div className="mt-4">
                  <h4 className="font-medium mb-2">备注信息：</h4>
                  <div className="p-3 bg-gray-50 rounded border">
                    {orderDetail.notes}
                  </div>
                </div>
              )}
            </Card>

            {/* 客户信息 */}
            <Card title={<><UserOutlined className="mr-2" />客户信息</>} size="small">
              <Descriptions column={2} size="small">
                <Descriptions.Item label="用户名">{orderDetail.customerInfo?.username}</Descriptions.Item>
                <Descriptions.Item label="昵称">{orderDetail.customerInfo?.nickname || '-'}</Descriptions.Item>
                <Descriptions.Item label="邮箱">{orderDetail.customerInfo?.email}</Descriptions.Item>
                <Descriptions.Item label="电话">{orderDetail.customerInfo?.phone || '-'}</Descriptions.Item>
              </Descriptions>
              
              {orderDetail.shipping_address && (
                <div className="mt-4">
                  <h4 className="font-medium mb-2">收货地址：</h4>
                  <div className="p-3 bg-gray-50 rounded border">
                    {orderDetail.shipping_address}
                  </div>
                </div>
              )}
            </Card>

            {/* 商品信息 */}
            <Card title="商品清单" size="small">
              <List
                dataSource={orderDetail.items || []}
                renderItem={(item: OrderItem) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={
                        <div className="w-16 h-16 bg-gray-200 rounded flex items-center justify-center">
                          {item.productInfo?.image_url || item.configInfo?.image_url ? (
                            <img 
                              src={item.productInfo?.image_url || item.configInfo?.image_url} 
                              alt="商品图片"
                              className="w-full h-full object-cover rounded"
                            />
                          ) : (
                            <span className="text-gray-400 text-xs">暂无图片</span>
                          )}
                        </div>
                      }
                      title={
                        <div>
                          <div className="font-medium">
                            {item.productInfo?.name || item.configInfo?.name || item.product_name || item.config_name}
                          </div>
                          <div className="text-sm text-gray-500">
                            类型: {item.product_id ? '商品' : '配置'} | 
                            分类: {item.productInfo?.category || item.configInfo?.category || '-'}
                          </div>
                        </div>
                      }
                      description={
                        <div className="flex justify-between items-center">
                          <span>数量: {item.quantity}</span>
                          <span>单价: ¥{formatAmount(item.unit_price)}</span>
                          <span className="font-medium">小计: ¥{formatAmount(item.quantity * item.unit_price)}</span>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
              
              {/* 订单汇总 */}
              {orderDetail.summary && (
                <div className="mt-4 p-4 bg-gray-50 rounded">
                  <div className="flex justify-between items-center text-sm">
                    <span>商品种类: {orderDetail.summary.itemCount}</span>
                    <span>商品总数: {orderDetail.summary.totalQuantity}</span>
                    <span>商品小计: ¥{formatAmount(orderDetail.summary.subtotal)}</span>
                    <span className="text-lg font-medium text-red-500">
                      订单总额: ¥{formatAmount(orderDetail.summary.totalAmount)}
                    </span>
                  </div>
                </div>
              )}
            </Card>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default OrderList; 